from GUI.Widget.Gradient import GradientController
import numpy as np


class ColormapGradientController(GradientController):
    def toColormap(self):
        """
        将渐变器上的颜色映射为[0-255]的颜色表
        :return:
        """
        colormap = np.zeros((3, 256))
        if not self.gradient:
            return colormap
        stops = self.gradient.stops()
        # 找左右端点
        n = 0
        spin = 1 / 255
        rate = 0
        for i in range(0, len(stops) - 1):
                color1 = stops[i][1]
                color2 = stops[i + 1][1]
                delta = stops[i + 1][0] - stops[i][0]
                while rate < stops[i + 1][0]:
                    k = (rate - stops[i][0]) / delta
                    colormap[0, n] = round(color1.red() + (color2.red() - color1.red()) * k)
                    colormap[1, n] = round(color1.green() + (color2.green() - color1.green()) * k)
                    colormap[2, n] = round(color1.blue() + (color2.blue() - color1.blue()) * k)
                    n = n+1
                    rate = rate + spin

        # 终点
        n = 255
        color = stops[-1][1]
        colormap[0, n] = round(color.red())
        colormap[1, n] = round(color.green())
        colormap[2, n] = round(color.blue())
        colormap = np.uint8(np.clip(colormap, 0, 255))
        return colormap

    def updateSlot(self):
        colormap = self.toColormap()
        self.parent().applyCustomColormap(colormap)

